<?php


namespace app\job;

use app\common\service\member\MemberAccountService;
use app\common\service\webscoket\CacheRedisService;
use app\common\service\member\SettingService;
use think\queue\Job;
use think\facade\Log;
use think\facade\Db;

/**
 * 系统派单自动匹配买家
 */
class OrderAssignJob
{
    public function fire(Job $job, $order)
    {
        try {
            $setting = SettingService::info('order_effective_time');
            if(!isset($setting['order_effective_time']) || $setting['order_effective_time']<=0){
                $setting['order_effective_time'] = 60*60*24;//若没有设置，则默认一天
            }else{
                $setting['order_effective_time'] +=10;//加10秒损耗时间
            }
            //匹配买家
            $member_account = MemberAccountService::getAccountByOrder($order);
            foreach ($member_account as $k=>$v){
                if($k==0){
                    $res = Db::name('shop_order')
                            ->where('id',$order['id'])
                            ->update([
                                'pending_member_id'=>$v['member_id'],
                                'pending_member_account_id'=>$v['member_account_id'],
                                'pending_time'=>date('Y-m-d H:i:s', (time()+$setting['order_effective_time'])),
                            ]);
                    //通知用户有待接订单
                    CacheRedisService::set('OrderAssignListener_'.$v['member_id'],$order['id'],$setting['order_effective_time']);
                    Log::write($order['id']."系统自动派单给：".$v['member_account_id']);
                    break;
                }
            }
            //删除缓存
            CacheRedisService::sRem('OrderAssignListener',$order['id']);
            Log::write("删除缓存：".$order['id']);
        } catch (\Exception $e) {
            Log::error("系统派单自动匹配买家：".print_r($order,true)."内容：".$e->getMessage());
        }
        $job->delete();
    }
}
